package org.air.demo.filter;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import java.util.UUID;

@Activate(group = {Constants.PROVIDER,Constants.CONSUMER},order = -99999)
public class GlobalTraceFilter implements Filter {

	private static final Logger log = LoggerFactory.getLogger(GlobalTraceFilter.class);
	private static final String KEY_TRACE_ID = "traceId";

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
		String traceId = invocation.getAttachment(KEY_TRACE_ID);
        if(StringUtils.isBlank(traceId)){
            traceId = UUID.randomUUID().toString();
        }
        MDC.put("request_id",traceId);
		RpcContext.getContext().setAttachment(KEY_TRACE_ID, traceId);
		log.info("Thread name : {}", Thread.currentThread().getName());
		return invoker.invoke(invocation);
    }
}
